package com.tian.core.thread;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Wenqiang Yang
 * @date 2018/01/19
 */
public class ExecutorPool {
    private static volatile ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private ExecutorPool(){}
    public static ThreadPoolTaskExecutor getInstance() {
        ThreadPoolTaskExecutor result = threadPoolTaskExecutor;
        if(null == result) {
            synchronized (ExecutorPool.class){
                result = threadPoolTaskExecutor;
                if(null == result) {
                    threadPoolTaskExecutor = result = new ThreadPoolTaskExecutor();
                    // 队列最大长度
                    threadPoolTaskExecutor.setQueueCapacity(1000);
                    // 核心线程数
                    threadPoolTaskExecutor.setCorePoolSize(20);
                    // 最大线程数
                    threadPoolTaskExecutor.setMaxPoolSize(100);
                    // 线程池维护线程所允许的空闲时间
                    threadPoolTaskExecutor.setKeepAliveSeconds(5000);
                    // 线程池对拒绝任务(无线程可用)的处理策略,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
                    threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
                    threadPoolTaskExecutor.initialize();
                }
            }
        }
        return result;
    }
}
